package br.ufal.ic.fracao.agent.avaliation;

import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;

public class ReplyBehaviourAvaliator extends CyclicBehaviour{

	private AvaliatorAgent avaliator;
	
	public ReplyBehaviourAvaliator(AvaliatorAgent avaliator) {
		this.avaliator = avaliator;
	}
	
	@Override
	public void action(){
		ACLMessage message = this.avaliator.receive();
		if(message != null){	
			String[] messageContent = message.getContent().split(":");					
			if(messageContent.length == 2){
				if(!messageContent[0].equals("SimplificationAgent")){
					this.updateExpressionList(messageContent[1]);
					this.avaliator.setContinueResolution(true);
				}else{
					this.updateExpressionListSimplification(messageContent[1]);
					this.avaliator.setResult(messageContent[1]);
					//this.avaliator.doDelete();
				}				
			}
			System.out.println("Agente " + messageContent[0] + " para Agente Avaliador: " + message.getContent());			
		}
	}
	
	protected AID[] getAIDs(String name, String service){
		DFAgentDescription dfAgentDescription = new DFAgentDescription();
		ServiceDescription serviceDescription = new ServiceDescription();
		serviceDescription.setName(name);
		serviceDescription.setType(service);
		dfAgentDescription.addServices(serviceDescription);
		try{
			DFAgentDescription results[] = DFService.search(this.avaliator, dfAgentDescription); 
			AID[] aid = new AID[results.length];
			for (int i = 0; i < results.length; i++) {
				aid[i] = results[i].getName();
			}
			return aid;
		}catch(FIPAException e){
			return null;
		}
	}
	
	public void updateExpressionListSimplification(String newValue){
		avaliator.getExpressionList().set(0, newValue);
	}
	
	public void updateExpressionList(String  newValue){
		avaliator.getExpressionList().remove(avaliator.getPosition() - 1);
		avaliator.getExpressionList().remove(avaliator.getPosition());
		avaliator.getExpressionList().set(avaliator.getPosition() - 1, newValue);
	}

}
